public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    //给定一个带有头结点 head 的非空单链表，返回链表的中间结点。如果有两个中间结点，则返回第二个中间结点
    public ListNode middleNode(ListNode head) {
        //这两段不必要，如果head为空，那么fast就为空，也就不会进入循环
        if(head == null)return null;
        if(head.next == null)return head;

        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast= fast.next.next;
            slow = slow.next;

        }
        return slow;
    }

    public ListNode KeyNode(ListNode head, int key){
        ListNode fast = head;
        ListNode slow = head;
        if (key <= 0 || head != null){
            return null;
        }
        for (int i = 0; i < key - 1; i++) {
            fast = fast.next;
            if (fast == null){
                return null;
            }
        }
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}